const express = require('express')
const router = express.Router();
const User = require('../controllers/user')
const Setting = require('../setting')
const Token = require('../token')

router.post('/login', ((req, res) => {
    let {name, password} = req.body
    if(!name || !password) {
        res.send({code: Setting.MissParameter, message: '缺失参数'})
    }else {
        User.login(name, (data) => {
            if(data) {
                if(data.password !== password) res.send({code: Setting.PasswordError, message: '密码错误'})
                else {
                    Token.setToken(data.name, data.id).then((token) => {
                        res.send({code: Setting.Success, token: token, data: data})
                    })
                }
            }else {
                res.send({code: Setting.NoOneFound, message: '没有该用户'})
            }
        })
    }
}))

router.post('/update', ((req, res) => {
  let {name, password} = req.body
  if(!name || !password) res.send({code: Setting.MissParameter, message: '缺失参数'})
  else {
    User.updatePassword(name, password)
  }
  res.send({code:Setting.Success, message: 'success'})
}))
module.exports = router;
